﻿////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// <copyright>Copyright 2008-2011 Andreas Huber Doenni</copyright>
// Distributed under the GNU General Public License version 2 (GPLv2).
// See accompanying file License.txt or copy at http://phuse.codeplex.com/license.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

namespace Phuse.Mime
{
    using System.Collections.Generic;

    /// <summary>Processes an unstructured header field.</summary>
    internal sealed class UnstructuredHeaderFieldBodyProcessor : HeaderFieldBodyProcessor
    {
        private readonly List<char> body = new List<char>(128);
        private int lastNonWhitespaceCount;
        private readonly UnstructuredHeaderField result;

        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        internal UnstructuredHeaderFieldBodyProcessor(string fieldName)
        {
            this.result = new UnstructuredHeaderField(fieldName);
        }

        internal sealed override void ProcessNormalBodyEvent(byte ev)
        {
            this.ProcessEvent(ev);
        }

        internal sealed override void ProcessQuotedBodyEvent(byte ev, bool isQuoteChar)
        {
            this.ProcessEvent(ev);
        }

        internal sealed override void ProcessCommentBodyEvent(byte ev)
        {
            this.ProcessEvent(ev);
        }

        internal sealed override HeaderField GetHeaderField()
        {
            this.result.Body = new string(this.body.ToArray(), 0, this.lastNonWhitespaceCount);
            return this.result;
        }

        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        private void ProcessEvent(byte ev)
        {
            this.body.Add((char)ev);

            switch (ev)
            {
                case (byte)' ':
                case (byte)'\t':
                    break;
                default:
                    this.lastNonWhitespaceCount = this.body.Count;
                    break;
            }
        }
    }
}
